package com.qianxing.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianxing.exceptionhandler.ResponseException;
import com.qianxing.mapper.TbUserInfoMapper;
import com.qianxing.po.TbTravelDataPO;
import com.qianxing.po.TbUserInfoPO;
import com.qianxing.service.TbTravelDataService;
import com.qianxing.mapper.TbTravelDataMapper;
import com.qianxing.utils.MultipartFileToFileUtils;
import com.qianxing.utils.TencentCOSFileUpload;
import com.qianxing.vo.TbTravelDataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.qianxing.utils.RedisContanct.LOGIN_USER_KEY;

/**
 * @author JasonLong
 * @description 针对表【tb_travel_data(游记数据表)】的数据库操作Service实现
 * @createDate 2023-07-09 22:13:20
 */
@Service
public class TbTravelDataServiceImpl extends ServiceImpl<TbTravelDataMapper, TbTravelDataPO>
        implements TbTravelDataService {

    @Autowired
    private TbTravelDataMapper tbTravelDataMapper;

    @Autowired
    private TbUserInfoMapper userInfoMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${upload.travelServerUrl}")
    private String travelServerUrl;

    @Override
    public List<?> getTravel() {

        List<TbTravelDataVO> tbTravelDataVOS = tbTravelDataMapper.selectList(null).stream().map(m -> {
            TbTravelDataVO tbTravelDataVO = new TbTravelDataVO();
            tbTravelDataVO.setTravelTitle(m.getTravelTitle());
            tbTravelDataVO.setTravelMsg(m.getTravelMsg());
            tbTravelDataVO.setUserNickname(m.getUserNickname());
            //反序列化
            tbTravelDataVO.setTravelImg(JSONObject.parseArray(m.getTravelImg()));
            tbTravelDataVO.setTravelClickNum(m.getTravelClickNum());
            tbTravelDataVO.setTravelId(m.getTravelId());
            return tbTravelDataVO;
        }).collect(Collectors.toList());

        return tbTravelDataVOS;
    }

    @Override
    public ResponseException saveTravelFile(String travelId, String travelTitle, String travelMsg, String token, MultipartFile files) {
        System.out.println("进入文件存储:");
        if (StrUtil.isBlank(token)) {
            return ResponseException.error("500", "token为空");
        }
        //拿到互斥锁
        String originalFilename = files.getOriginalFilename();
        //获取文件后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
        //文件重命名
        String newFileName = UUID.randomUUID().toString() + substring;

        //TODO 将Multiple类型转为File类型
        File file = MultipartFileToFileUtils.multipartFileToFile(files);

        //TODO 将文件存储到COS
        String uploadFilePath = TencentCOSFileUpload.uploadfile(file, newFileName, travelServerUrl);

        //TODO 通过token获取用户信息
        String userOpenId = stringRedisTemplate.opsForValue().get(LOGIN_USER_KEY + token);

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("user_openid", userOpenId);

        //拿到用户数据
        TbUserInfoPO tbUserInfoPO = userInfoMapper.selectOne(wrapper);

        //TODO 封装数据
        TbTravelDataPO tbTravelDataPO = new TbTravelDataPO();
        tbTravelDataPO.setTravelId(travelId);
        //序列化
        List list = new ArrayList<>();
        list.add(uploadFilePath);
        tbTravelDataPO.setTravelImg(JSON.toJSONString(list));
        tbTravelDataPO.setUserOpenid(userOpenId);
        tbTravelDataPO.setTravelTitle(travelTitle);
        tbTravelDataPO.setTravelMsg(travelMsg);
        List list1 = new ArrayList<>();
        list1.add(newFileName);
        tbTravelDataPO.setTravelImgName(JSON.toJSONString(list1));
        tbTravelDataPO.setUserNickname(tbUserInfoPO.getUserNickname());

        //TODO 将数据存入数据库
        boolean save = save(tbTravelDataPO);
        if (!save) {
            return ResponseException.error("500", "服务器内部错误！");
        }
        System.out.println(newFileName);
        System.out.println(substring);
        return ResponseException.success();
    }

    /**
     * 生成随机ID
     *
     * @return
     */
    @Override
    public String getTravelId() {

        String string = UUID.randomUUID().toString();

        //自定义格式ID
        String Key = "travel-" + string;

        return Key;
    }
}